package com.card.hwatt.controllers;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.UUID;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import com.card.hwatt.dto.PageParam;
import com.card.hwatt.dto.PageResult;
import com.card.hwatt.dto.ReturnValue;
import com.card.hwatt.service.AdminService;
import com.card.hwatt.service.EmployeeService;
import com.card.hwatt.service.UserService;

/**
 * 主页
 * @author Administrator
 *
 */
@Controller
@Scope("prototype")
public class MainController extends BaseController{

	private static final String CODE_IMG = "code";

	@Autowired
	@Qualifier("adminService")
	private AdminService adminService;

	@Autowired
	@Qualifier("userService")
	private UserService userService;

	@Autowired
	@Qualifier("employeeService")
	private EmployeeService employeeService;

	@RequestMapping("/index")
	public String index(Model model) {
		return "index";
	}

	@RequestMapping("/user")
	public String user(HttpServletRequest request, ModelMap modelMap) {
		HttpSession session = request.getSession();
		modelMap.put("isAdmin", session.getAttribute("isAdmin"));
		return "userindex";
	}

	@RequestMapping("/login")
	public @ResponseBody
	ReturnValue login(String name, String password, String code,
			HttpServletRequest request) {
		ReturnValue result = new ReturnValue();

		if (StringUtils.isEmpty(password) || StringUtils.isEmpty(name)
				|| StringUtils.isEmpty(code)) {
			result.message = "输入不完全";
			return result;
		}

		Object imgCode = request.getSession().getAttribute(CODE_IMG);
		if (imgCode == null
				|| !code.toUpperCase().equals(imgCode.toString().toUpperCase())) {
			result.message = "验证码不正确";
			return result;
		}

		com.card.hwatt.entity.Admin admin = getAdminByName(name);
		if (admin == null || admin.password == null) {
			result.message = "用户名不存在";
			return result;
		}

		String md5 = getMD5(admin.id + password);

		if (!admin.password.toUpperCase().equals(md5)) {
			result.message = "密码错误";
			return result;
		}

		request.getSession().setAttribute("logon", true);
		result.isSucess = true;
		result.message = "ok";
		return result;

	}

	@RequestMapping("/changedUserPassword")
	public @ResponseBody
	ReturnValue changedUserPassword(HttpServletRequest request,
			String password, String oldPassword) {
		ReturnValue result = new ReturnValue();
		if (oldPassword == null) {
			result.message = "请输入原始密码";
			return result;
		}
		if (password == null) {
			result.message = "请输入新密码";
			return result;
		}

		Object employeeId = request.getSession().getAttribute("userId");
		if (employeeId == null) {
			result.message = "请登录";
			return result;
		}
		Long id = (Long) employeeId;
		com.card.hwatt.entity.Employee employee = employeeService.get(id);
		if (employee == null) {
			result.message = "请登录";
			return result;
		}

		if (employee.user == null) {

			if (!"123456".equals(oldPassword)) {
				result.message = "原始密码不正确，请重新输入！";
				return result;
			}

			employee.user = new com.card.hwatt.entity.User();
			employee.user.id = UUID.randomUUID();
			employee.user.employee = employee;
			String md5 = getMD5(employee.id + password);
			employee.user.password = md5;
			userService.save(employee.user);
		} else {
			if (employee.user.password == null) {
				if (!"123456".equals(oldPassword)) {
					result.message = "原始密码不正确，请重新输入！";
					return result;
				}
			} else {
				String md5 = getMD5(employee.id + oldPassword);
				if (!employee.user.password.toUpperCase().equals(md5)) {
					result.message = "原始密码不正确，请重新输入！";
					return result;
				}
			}
			String md5 = getMD5(employee.id + password);
			employee.user.password = md5;
			userService.update(employee.user);
		}

		result.message = "ok";
		result.isSucess = true;
		return result;
	}

	@RequestMapping("/user/login")
	public @ResponseBody
	ReturnValue userLogin(String name, String password, String code,
			HttpServletRequest request) {

		ReturnValue result = new ReturnValue();

		if (StringUtils.isEmpty(password) || StringUtils.isEmpty(name)
				|| StringUtils.isEmpty(code)) {
			result.message = "输入不完全";
			return result;
		}

		Object imgCode = request.getSession().getAttribute(CODE_IMG);
		if (imgCode == null
				|| !code.toUpperCase().equals(imgCode.toString().toUpperCase())) {
			result.message = "验证码不正确";
			return result;
		}

		List<Object> params = new ArrayList<Object>();
		params.add(name);
		List<com.card.hwatt.entity.Employee> employeeList = employeeService
				.loadAll(new PageParam(1, 1, "  employeeCode = ? ", params,
						" name ")).rows;
		if (employeeList.size() == 0) {
			result.message = "用户名不存在";
			return result;
		}

		com.card.hwatt.entity.Employee employee = employeeList.get(0);
		if (employee.user == null || employee.user.password == null) {
			if (!"123456".equals(password)) {
				result.message = "密码错误";
				return result;
			}
		} else {
			String md5 = getMD5(employee.id + password);
			if (!employee.user.password.toUpperCase().equals(md5)) {
				result.message = "密码错误";
				return result;
			}
		}

		request.getSession().setAttribute("user", employee.name);
		request.getSession().setAttribute("userId", employee.id);
		request.getSession()
				.setAttribute("employeeCode", employee.employeeCode);
		request.getSession().setAttribute("departmentName",
				employee.department.name);
		request.getSession().setAttribute("departmentId",
				employee.department.id);
		if (employee.user != null && employee.user.isAdmin) {
			request.getSession().setAttribute("isAdmin", true);
		}

		result.isSucess = true;
		result.message = "ok";
		return result;
	}

	@RequestMapping("/user/logout")
	public String logOutUser(HttpServletRequest request) {
		request.getSession().removeAttribute("user");
		request.getSession().removeAttribute("userId");
		request.getSession().removeAttribute("employeeCode");
		request.getSession().removeAttribute("departmentName");
		request.getSession().removeAttribute("departmentId");
		if (request.getSession().getAttribute("isAdmin") != null) {
			request.getSession().removeAttribute("isAdmin");
		}

		return "redirect:/userindex.jsp";
	}

	private com.card.hwatt.entity.Admin getAdminByName(String name) {
		List<Object> params = new ArrayList<Object>();
		params.add(name);
		PageResult<com.card.hwatt.entity.Admin> list = adminService
				.loadAll(new PageParam(1, 1, " name = ? ", params, " name asc "));
		if (CollectionUtils.isNotEmpty(list.rows)) {
			return list.rows.get(0);
		}
		return null;
	}

	@RequestMapping("/logOut")
	public String logOut(HttpServletRequest request) {
		String root = "";
		request.getSession().removeAttribute("logon");
		return "redirect:" + root + "/index.jsp";
	}

	@RequestMapping("/imageCode")
	public void imageCode(HttpServletRequest request,
			HttpServletResponse response) {
		response.setHeader("Pragma", "No-cache");
		response.setHeader("Cache-Control", "no-cache");
		response.setDateHeader("Expires", 0);
		// 表明生成的响应是图片
		response.setContentType("image/jpeg");

		int width = 100, height = 18;
		BufferedImage image = new BufferedImage(width, height,
				BufferedImage.TYPE_INT_RGB);

		Graphics g = image.getGraphics();
		Random random = new Random();
		g.setColor(getRandColor(200, 250));
		g.fillRect(1, 1, width - 1, height - 1);
		g.setColor(new Color(102, 102, 102));
		g.drawRect(0, 0, width - 1, height - 1);

		Font font = new Font("Times New Roman", Font.PLAIN, 17);
		g.setFont(font);

		g.setColor(getRandColor(160, 200));

		// 画随机线
		for (int i = 0; i < 155; i++) {
			int x = random.nextInt(width - 1);
			int y = random.nextInt(height - 1);
			int xl = random.nextInt(6) + 1;
			int yl = random.nextInt(12) + 1;
			g.drawLine(x, y, x + xl, y + yl);
		}

		// 从另一方向画随机线
		for (int i = 0; i < 70; i++) {
			int x = random.nextInt(width - 1);
			int y = random.nextInt(height - 1);
			int xl = random.nextInt(12) + 1;
			int yl = random.nextInt(6) + 1;
			g.drawLine(x, y, x - xl, y - yl);
		}

		// 生成随机数,并将随机数字转换为字母
		String code = "";
		for (int i = 0; i < 4; i++) {
			int itmp = random.nextInt(26) + 65;
			char ctmp = (char) itmp;
			code += String.valueOf(ctmp);
			g.setColor(new Color(20 + random.nextInt(110), 20 + random
					.nextInt(110), 20 + random.nextInt(110)));
			g.drawString(String.valueOf(ctmp), 15 * i + 10, 16);
		}

		HttpSession session = request.getSession(true);
		session.setAttribute(CODE_IMG, code);
		g.dispose();
		try {
			ImageIO.write(image, "JPEG", response.getOutputStream());
		} catch (Exception e) {
		}
	}

	private Color getRandColor(int fc, int bc) {
		Random random = new Random();
		if (fc > 255)
			fc = 255;
		if (bc > 255)
			bc = 255;
		int r = fc + random.nextInt(bc - fc);
		int g = fc + random.nextInt(bc - fc);
		int b = fc + random.nextInt(bc - fc);
		return new Color(r, g, b);
	}

	private String getMD5(String src) {
		if (StringUtils.isEmpty(src)) {
			return null;
		}
		byte[] source = src.getBytes();
		String s = null;
		char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
				'a', 'b', 'c', 'd', 'e', 'f' };// 用来将字节转换成16进制表示的字符
		try {
			java.security.MessageDigest md = java.security.MessageDigest
					.getInstance("MD5");
			md.update(source);
			byte tmp[] = md.digest();// MD5 的计算结果是一个 128 位的长整数，
			// 用字节表示就是 16 个字节
			char str[] = new char[16 * 2];// 每个字节用 16 进制表示的话，使用两个字符， 所以表示成 16
			// 进制需要 32 个字符
			int k = 0;// 表示转换结果中对应的字符位置
			for (int i = 0; i < 16; i++) {// 从第一个字节开始，对 MD5 的每一个字节// 转换成 16
				// 进制字符的转换
				byte byte0 = tmp[i];// 取第 i 个字节
				str[k++] = hexDigits[byte0 >>> 4 & 0xf];// 取字节中高 4 位的数字转换,// >>>
				// 为逻辑右移，将符号位一起右移
				str[k++] = hexDigits[byte0 & 0xf];// 取字节中低 4 位的数字转换

			}
			s = new String(str);// 换后的结果转换为字符串

		} catch (Exception e) {
			e.printStackTrace();
		}
		return s.toUpperCase();
	}
}
